package com.example.logining.domain.vo;

import com.alibaba.fastjson.annotation.JSONField;
import com.example.logining.domain.pojo.SysUser;
import com.example.logining.domain.pojo.User;
import io.jsonwebtoken.lang.Collections;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @title: LoginUser
 * @author: wywang
 * @date: 2024/11/13
 * @description:
 **/
@Data
@NoArgsConstructor
public class LoginUser implements UserDetails {

    private SysUser user;

    private List<String> permissions;

    public LoginUser(SysUser user, List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }


    private transient List<SimpleGrantedAuthority> authorities;  // 不序列到redis中

    /**
     * 重写getAuthorities方法，返回用户权限
     * 把permissions中的String类型的权限信息转换为SimpleGrantedAuthority对象
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {

        // 优化，如果已经获取到权限信息，就直接返回，不用再次转换
        if(!Collections.isEmpty(authorities)){
            return authorities;
        }

        authorities = permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        return authorities;
    }

    /**
     * 用户权限变更以后
     * 清理权限缓存
     */
    public void clearAuthoritiesCache() {
        this.authorities = null;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
